#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
字典管理API - v1版本
提供字典数据查询服务
"""

from flask import Blueprint, request, jsonify
from app.utils.response import success_response, error_response
from app.services.dict_service import DictService
from app.api_docs.dict import dict_api_docs
from typing import Dict, Any

# 创建蓝图
dict_bp = Blueprint('dict_v1', __name__, url_prefix='/api/v1/dict')


@dict_bp.route('/categories', methods=['GET'])
def get_dict_categories():
    """
    获取字典分类列表
    ---
    tags:
      - 字典管理
    summary: 获取所有字典分类列表
    description: 获取系统中所有启用的字典分类，包含分类信息和用途标识
    responses:
      200:
        description: 获取成功
        content:
          application/json:
            schema:
              type: object
              properties:
                code:
                  type: integer
                  example: 200
                message:
                  type: string
                  example: "获取字典分类成功"
                data:
                  type: array
                  items:
                    type: object
                    properties:
                      id:
                        type: integer
                        description: 分类ID
                      dict_code:
                        type: string
                        description: 分类编码
                      dict_name:
                        type: string
                        description: 分类名称
                      dict_desc:
                        type: string
                        description: 分类描述
                      usage:
                        type: string
                        enum: [user_profile, mate_criteria, common]
                        description: 分类用途
                      sort_order:
                        type: integer
                        description: 排序
                      is_active:
                        type: boolean
                        description: 是否启用
    """
    try:
        categories = DictService.get_all_categories()
        return success_response(data=categories, message="获取字典分类成功")
    except Exception as e:
        return error_response(message=f"获取字典分类失败: {str(e)}")


@dict_bp.route('/items/<string:dict_code>', methods=['GET'])
def get_dict_items(dict_code: str):
    """
    根据字典编码获取字典项
    ---
    tags:
      - 字典管理
    summary: 获取指定字典的所有字典项
    description: 根据字典分类编码获取该分类下的所有字典项
    parameters:
      - in: path
        name: dict_code
        schema:
          type: string
        required: true
        description: 字典分类编码
        example: "education"
    responses:
      200:
        description: 获取成功
        content:
          application/json:
            schema:
              type: object
              properties:
                code:
                  type: integer
                  example: 200
                message:
                  type: string
                  example: "获取字典项成功"
                data:
                  type: array
                  items:
                    type: object
                    properties:
                      id:
                        type: integer
                        description: 字典项ID
                      dict_id:
                        type: integer
                        description: 字典分类ID
                      item_name:
                        type: string
                        description: 字典项名称
                      item_value:
                        type: string
                        description: 字典项值
                      item_desc:
                        type: string
                        description: 字典项描述
                      sort_order:
                        type: integer
                        description: 排序
                      is_active:
                        type: boolean
                        description: 是否启用
      404:
        description: 字典分类不存在
    """
    try:
        items = DictService.get_dict_items(dict_code)
        if not items:
            return error_response(message="字典分类不存在或无数据", code=404)
        
        return success_response(data=items, message="获取字典项成功")
    except Exception as e:
        return error_response(message=f"获取字典项失败: {str(e)}")


@dict_bp.route('/user-profile', methods=['GET'])
def get_user_profile_dicts():
    """
    获取用户资料相关字典
    ---
    tags:
      - 字典管理
    summary: 获取用户资料相关的所有字典
    description: 获取用户资料管理需要的所有字典数据，包括教育程度、职业、收入等
    responses:
      200:
        description: 获取成功
        content:
          application/json:
            schema:
              type: object
              properties:
                code:
                  type: integer
                  example: 200
                message:
                  type: string
                  example: "获取用户资料字典成功"
                data:
                  type: object
                  properties:
                    education:
                      type: array
                      description: 教育程度字典
                    marital_status:
                      type: array
                      description: 婚姻状况字典
                    occupation:
                      type: array
                      description: 职业字典
                    income_range:
                      type: array
                      description: 收入范围字典
                    housing_status:
                      type: array
                      description: 住房情况字典
                    car_status:
                      type: array
                      description: 车辆情况字典
                    smoking_habit:
                      type: array
                      description: 吸烟习惯字典
                    drinking_habit:
                      type: array
                      description: 饮酒习惯字典
                    personality_traits:
                      type: array
                      description: 性格特点字典
                    hobbies:
                      type: array
                      description: 兴趣爱好字典
    """
    try:
        dicts = DictService.get_user_profile_dicts()
        return success_response(data=dicts, message="获取用户资料字典成功")
    except Exception as e:
        return error_response(message=f"获取用户资料字典失败: {str(e)}")


@dict_bp.route('/mate-criteria', methods=['GET'])
def get_mate_criteria_dicts():
    """
    获取择偶条件相关字典
    ---
    tags:
      - 字典管理
    summary: 获取择偶条件相关的所有字典
    description: 获取择偶条件设置需要的所有字典数据，包括收入要求、教育要求等
    responses:
      200:
        description: 获取成功
        content:
          application/json:
            schema:
              type: object
              properties:
                code:
                  type: integer
                  example: 200
                message:
                  type: string
                  example: "获取择偶条件字典成功"
                data:
                  type: object
                  properties:
                    income_requirement:
                      type: array
                      description: 收入要求字典
                    education_requirement:
                      type: array
                      description: 教育要求字典
                    occupation_requirement:
                      type: array
                      description: 职业要求字典
                    marital_requirement:
                      type: array
                      description: 婚姻要求字典
                    housing_requirement:
                      type: array
                      description: 住房要求字典
                    smoking_requirement:
                      type: array
                      description: 吸烟要求字典
                    drinking_requirement:
                      type: array
                      description: 饮酒要求字典
    """
    try:
        dicts = DictService.get_mate_criteria_dicts()
        return success_response(data=dicts, message="获取择偶条件字典成功")
    except Exception as e:
        return error_response(message=f"获取择偶条件字典失败: {str(e)}")


@dict_bp.route('/search', methods=['GET'])
def search_dict_items():
    """
    搜索字典项
    ---
    tags:
      - 字典管理
    summary: 根据关键词搜索字典项
    description: 支持按关键词搜索字典项，可指定搜索范围
    parameters:
      - in: query
        name: keyword
        schema:
          type: string
        required: true
        description: 搜索关键词
        example: "本科"
      - in: query
        name: dict_codes
        schema:
          type: string
        required: false
        description: 限定搜索的字典分类编码，多个用逗号分隔
        example: "education,occupation"
    responses:
      200:
        description: 搜索成功
        content:
          application/json:
            schema:
              type: object
              properties:
                code:
                  type: integer
                  example: 200
                message:
                  type: string
                  example: "搜索字典项成功"
                data:
                  type: array
                  items:
                    type: object
                    properties:
                      id:
                        type: integer
                        description: 字典项ID
                      dict_id:
                        type: integer
                        description: 字典分类ID
                      item_name:
                        type: string
                        description: 字典项名称
                      item_value:
                        type: string
                        description: 字典项值
                      item_desc:
                        type: string
                        description: 字典项描述
                      sort_order:
                        type: integer
                        description: 排序
                      is_active:
                        type: boolean
                        description: 是否启用
      400:
        description: 参数错误
    """
    try:
        keyword = request.args.get('keyword', '').strip()
        if not keyword:
            return error_response(message="搜索关键词不能为空", code=400)
        
        dict_codes_param = request.args.get('dict_codes', '').strip()
        dict_codes = None
        if dict_codes_param:
            dict_codes = [code.strip() for code in dict_codes_param.split(',') if code.strip()]
        
        items = DictService.search_dict_items(keyword, dict_codes)
        return success_response(data=items, message="搜索字典项成功")
    except Exception as e:
        return error_response(message=f"搜索字典项失败: {str(e)}")


@dict_bp.route('/statistics', methods=['GET'])
def get_dict_statistics():
    """
    获取字典统计信息
    ---
    tags:
      - 字典管理
    summary: 获取字典系统统计信息
    description: 获取字典分类和字典项的统计数据
    responses:
      200:
        description: 获取成功
        content:
          application/json:
            schema:
              type: object
              properties:
                code:
                  type: integer
                  example: 200
                message:
                  type: string
                  example: "获取字典统计信息成功"
                data:
                  type: object
                  properties:
                    total_categories:
                      type: integer
                      description: 总分类数
                    total_items:
                      type: integer
                      description: 总字典项数
                    user_profile_categories:
                      type: integer
                      description: 用户资料分类数
                    mate_criteria_categories:
                      type: integer
                      description: 择偶条件分类数
                    common_categories:
                      type: integer
                      description: 通用分类数
    """
    try:
        stats = DictService.get_dict_statistics()
        return success_response(data=stats, message="获取字典统计信息成功")
    except Exception as e:
        return error_response(message=f"获取字典统计信息失败: {str(e)}") 